import React, { PropsWithChildren } from 'react';
import { usePermissions, useUserToken } from '@/store/userStore.ts';
import { useFlattenedRoutes } from '@/router/hooks';
import { Navigate, useLocation } from 'react-router-dom';

type Props = PropsWithChildren;

const AuthGuard: React.FC<Props> = ({ children }) => {
  const token = useUserToken();
  const location = useLocation();
  const routes = useFlattenedRoutes();
  const permissions = usePermissions() ?? [];

  const route = routes.find((route) => route.key === location.pathname);

  // If no token, redirect to login page
  if (!token) return <Navigate to={`login?redirect=${location.pathname}`} replace />;
  // If route is not found, render children
  if (!route) return children;
  // If route has no permissions, render children
  if (!route.permissions?.length) return <>{children}</>;
  // If user does not have required permissions, redirect to 403 page
  if (!route.permissions.every((perm) => permissions.includes(perm))) return <Navigate to="/403" />;

  return children;
};

export default AuthGuard;
